package com.itguigu.glimail.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.itguigu.common.to.mq.SeckillOrderTo;
import com.itguigu.common.utils.R;
import com.itguigu.glimail.oauth.vo.MemberRespVo;
import com.itguigu.glimail.seckill.feign.CouponFeignService;
import com.itguigu.glimail.seckill.feign.ProductFeignService;
import com.itguigu.glimail.seckill.interceptor.LoginUserInterceptor;
import com.itguigu.glimail.seckill.service.SeckillService;
import com.itguigu.glimail.seckill.to.SeckillSkuRedisTo;
import com.itguigu.glimail.seckill.vo.SeckillSessionWithSkus;
import com.itguigu.glimail.seckill.vo.SkuInfoVo;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;

    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";
    private final String SECKILL_CACHE_PREFIX = "seckill:skus:";

    @Override
    public void uploadSeckillSkuLatest3Days() {
        //扫描最近三天参与秒杀的活动商品
        R r = couponFeignService.latest3DaySession();
        if (r.getCode() == 0) {
            //上架商品
            List<SeckillSessionWithSkus> sessionData = r.getData(new TypeReference<List<SeckillSessionWithSkus>>() {

            });
            //缓存到redis
            //缓存活动信息
            saveSessionInfos(sessionData);
            //缓存活动的关联商品的信息
            saveSessionSkuInfos(sessionData);

        }
    }

    //返回当前时间可以参与的秒杀商品信息
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        //1. 确定当前时间属于哪个秒杀场次。
        long time = new Date().getTime();
        Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
        for (String key : keys) {
            String timeZone = key.replace(SESSIONS_CACHE_PREFIX, "");
            String[] split = timeZone.split("_");
            Long start = Long.parseLong(split[0]);
            Long end = Long.parseLong(split[1]);
            if (time >= start && time <= end) {
                //2、获取这个秒杀场次需要的所有商品信息
                List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                BoundHashOperations<String, String, String> hashOps =
                        redisTemplate.boundHashOps(SECKILL_CACHE_PREFIX);
                List<String> list = hashOps.multiGet(range);
                if (list != null && list.size() > 0) {
                    List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                        SeckillSkuRedisTo redisTo = JSON.parseObject((String) item, SeckillSkuRedisTo.class);
//                        redisTo.setRandomCode(null); 当前秒杀已经开始了 需要随机码
                        return redisTo;
                    }).collect(Collectors.toList());
                    return collect;
                }
                break;
            }
        }
        //2、获取这个秒杀场次需要的所有商品信息
        return null;
    }

    /**
     *
     * @param skuId
     * @return
     */
    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        //1、找到所有需要参与秒杀的商品的key
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SECKILL_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();
        if (keys!=null&&keys.size()>0) {
            String regx = "\\d_" + skuId;
            //6_4
            for (String key : keys) {
                if ( Pattern.matches(regx, key)) {
                    String json = hashOps.get(key);
                    SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
                    //处随机码
                    long currentTime = new Date().getTime();
                    Long startTime = redisTo.getStartTime();
                    Long endTime = redisTo.getEndTime();
                    if (currentTime>=startTime&&currentTime<=endTime) {

                    }else {
                        redisTo.setRandomCode(null);
                    }
                    return redisTo;
                }
            }
        }
        return null;

    }

    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * TODO 上架商品秒杀的时候  每一个数据都有过期时间
     * TODO 秒杀的后续  简化了收货地址
     * @param killId
     * @param key
     * @param num
     * @return
     */
    @Override
    public String seckill(String killId, String key, Integer num) {
        MemberRespVo respVo = LoginUserInterceptor.loginUser.get();

        //1获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps =
                redisTemplate.boundHashOps(SECKILL_CACHE_PREFIX);
        String json = hashOps.get(killId);
        if (!StringUtils.isEmpty(json)) {
            SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
            //校验合法性
            Long endTime = redisTo.getEndTime();
            Long startTime = redisTo.getStartTime();
            long time = new Date().getTime();
            //教研时间的合法性
            if (time>=startTime&&time<=endTime) {
                //2随机码校验和商品id
                String randomCode = redisTo.getRandomCode();
                String skuId = redisTo.getPromotionSessionId()+"_"+redisTo.getSkuId();
                if (randomCode.endsWith(key) && killId.equals(skuId)) {
                    //合法
                    //验证购物数量
                    if (num<=redisTo.getSeckillLimit()) {
                        //验证这个人是否买过  幂等性
                        //只要买过  就在redis中占位记录 userid_sessionId_skuId
                        String redisKey = respVo.getId() + "_" + skuId;
                        //自动过期
                        long ttl = endTime - time;
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (aBoolean) {
                            //成功 说明没有买过
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                                boolean b = semaphore.tryAcquire(num);
                                if (b) {
                                    //秒杀成功
                                    //快速下单 发送mq消息
                                    String timeId = IdWorker.getTimeId();
                                    SeckillOrderTo seckillTo = new SeckillOrderTo();
                                    seckillTo.setOrderSn(timeId);
                                    seckillTo.setMemberId(respVo.getId());
                                    seckillTo.setNum(num);
                                    seckillTo.setPromotionSessionId(redisTo.getPromotionSessionId());
                                    seckillTo.setSkuId(redisTo.getSkuId());
                                    seckillTo.setSeckillPrice(redisTo.getSeckillPrice());
                                    rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order",seckillTo);
                                    return timeId;
                                }else {
                                    return null;
                                }
                        }else {
                            //失败 说明买过
                            //TODO 判断数量
                            return null;
                        }
                    }
                } else {

                }

            }else {
                return null;
            }
        }else {
            return null;
        }
        return null;
    }

    private void saveSessionInfos(List<SeckillSessionWithSkus> sessionData) {
        sessionData.stream().forEach(session -> {
            long startTime = session.getStartTime().getTime();
            long endTime = session.getEndTime().getTime();
            String key = SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;
            List<String> collect = session.getRelationSkus().stream().map(seckillSkuRelationVo -> seckillSkuRelationVo.getPromotionSessionId().toString() + "_" + seckillSkuRelationVo.getSkuId().toString()).collect(Collectors.toList());

            Boolean hasKey = redisTemplate.hasKey(key);
            if (!hasKey) {
                //缓存活动信息
                redisTemplate.opsForList().leftPushAll(key, collect);
            }


        });
    }

    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    RedissonClient redissonClient;
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";//商品随机码

    private void saveSessionSkuInfos(List<SeckillSessionWithSkus> sessionData) {
        sessionData.stream().forEach(session -> {
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SECKILL_CACHE_PREFIX);
            //4.商品的随机码  防止攻击
            String token = UUID.randomUUID().toString().replace("-", "");
            session.getRelationSkus().stream().forEach(seckillSkuRelationVo -> {
                if (!ops.hasKey(seckillSkuRelationVo.getPromotionSessionId().toString() + "_" + seckillSkuRelationVo.getSkuId().toString())) {
                    //缓存商品信息;
                    SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                    //1sku的基本数据
                    R skuInfo = productFeignService.getSkuInfo(seckillSkuRelationVo.getSkuId());
                    if (skuInfo.getCode() == 0) {
                        SkuInfoVo info = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        redisTo.setSkuInfo(info);
                    }
                    //2sku的秒杀信息
                    BeanUtils.copyProperties(seckillSkuRelationVo, redisTo);
                    //3设置当前商品的秒杀开始时间
                    redisTo.setStartTime(session.getStartTime().getTime());
                    redisTo.setEndTime(session.getEndTime().getTime());
                    redisTo.setRandomCode(token);
                    String jsonString = JSON.toJSONString(redisTo);
                    System.out.println(redisTo);
                    ops.put(seckillSkuRelationVo.getPromotionSessionId().toString() + "_" + seckillSkuRelationVo.getSkuId().toString(), jsonString);
                    //如果当前这个场次的商品库存信息已经上架就不需要上架
                    //引入分布式的信号量
                    //5、使用库存作为分布式的信号量  一大作用:限流
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    //商品可以秒杀的数量作为信号量
                    semaphore.trySetPermits(seckillSkuRelationVo.getSeckillCount());
                }
            });
        });

    }

}
